package com.example.demo.controller;

import com.example.demo.entity.BookCategory;
import com.example.demo.mapper.BookCategoryMapper;
import com.example.demo.utils.PagingResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/book-category") // 控制器的前缀地址
public class BookCategoryController {
    @Autowired
    BookCategoryMapper bookCategoryMapper;

    /**
     * 获取分页的图书分类数据
     * @param limit 每页数量
     * @param offset 偏移量
     * @param field 搜索字段
     * @param code 搜索关键词
     * @return 分页结果
     */
    @GetMapping("/list")
    public PagingResult<BookCategory> select(
            @RequestParam(required = false, name = "limit", defaultValue = "10") int limit,
            @RequestParam(required = false, name = "offset", defaultValue = "0") int offset,
            @RequestParam(required = false, name = "field") String field,
            @RequestParam(required = false, name = "code") String code
    ) {
        List<BookCategory> bookCategoryList;
        int total;
        
        if (field != null && code != null && !code.trim().isEmpty()) {
            bookCategoryList = bookCategoryMapper.findByPageAndSearch(offset, limit, field, code);
            total = bookCategoryMapper.countBySearch(field, code);
        } else {
            bookCategoryList = bookCategoryMapper.findByPage(offset, limit);
            total = bookCategoryMapper.count();
        }
        
        return new PagingResult<BookCategory>(bookCategoryList, total);
    }

    /**
     * 获取所有图书分类
     * @return 图书分类列表
     */
    @GetMapping("/all")
    public List<BookCategory> getAll() {
        return bookCategoryMapper.findAll();
    }

    /**
     * 根据ID获取图书分类
     * @param id 分类ID
     * @return 图书分类对象
     */
    @GetMapping("/{id}")
    public BookCategory getById(@PathVariable("id") int id) {
        return bookCategoryMapper.findById(id);
    }

    /**
     * 添加图书分类
     * @param bookCategory 图书分类对象
     * @return 影响行数
     */
    @PostMapping("/add")
    public int add(@RequestBody BookCategory bookCategory) {
        return bookCategoryMapper.insert(bookCategory);
    }

    /**
     * 更新图书分类
     * @param bookCategory 图书分类对象
     * @return 影响行数
     */
    @PutMapping("/update")
    public int update(@RequestBody BookCategory bookCategory) {
        return bookCategoryMapper.update(bookCategory);
    }

    /**
     * 删除图书分类
     * @param id 分类ID
     * @return 影响行数
     */
    @DeleteMapping("/delete/{id}")
    public int delete(@PathVariable("id") int id) {
        return bookCategoryMapper.delete(id);
    }
}